package com.linxiao.call.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.annotation.Resource;

import cn.hutool.core.util.DesensitizedUtil;
import com.alibaba.fastjson2.JSON;
import com.linxiao.call.domain.CrmCallBackCdr;
import com.linxiao.call.mapper.CrmCallBackCdrMapper;
import com.linxiao.call.service.ICrmCallBackCdrService;
import com.linxiao.call.vo.CrmCallBackCustomerInfo;
import com.linxiao.call.vo.QueryCrmCallBackCustomerInfoVO;
import com.ruoyi.system.manager.AdminManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IdSeqGenerator;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 回呼话单Service业务层处理
 *
 * @author qiqi
 * @date 2022-04-12
 */
@Service
public class CrmCallBackCdrServiceImpl implements ICrmCallBackCdrService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private CrmCallBackCdrMapper crmCallBackCdrMapper;
    @Autowired
    private ISysDeptService sysDeptService;
    @Resource
    private AdminManager adminManager;
    @Autowired
    private ISysDeptService deptService;
    /**
     * 查询回呼话单
     *
     * @param id 回呼话单主键
     * @return 回呼话单
     */
    @Override
    @DataScope(deptAlias = "c")
    public CrmCallBackCdr selectCrmCallBackCdrById(Long id, String cdrMainUniqueId) {
        CrmCallBackCdr crmCallBackCdr = crmCallBackCdrMapper.selectCrmCallBackCdrById(id,cdrMainUniqueId);
        if(Objects.nonNull(crmCallBackCdr)){
            crmCallBackCdr.setCdrId(crmCallBackCdr.getId()+"");
            String endTime = StringUtils.isNotEmpty(crmCallBackCdr.getCdrEndTime()) ? crmCallBackCdr.getCdrEndTime() :"";
            String brideTime = StringUtils.isNotEmpty(crmCallBackCdr.getCdrBridgeTime()) ? crmCallBackCdr.getCdrBridgeTime() :"";
            crmCallBackCdr.setCdrEndTimeCdrBridgeTime(endTime + "-" + brideTime);
        }

        return crmCallBackCdr;
    }

    /**
     * 查询回呼话单列表
     *
     * @param crmCallBackCdr 回呼话单
     * @return 回呼话单
     */
    @Override
    @DataScope(deptAlias = "c")
    public List<CrmCallBackCdr> selectCrmCallBackCdrList(CrmCallBackCdr crmCallBackCdr) {
        List<CrmCallBackCdr> crmCallBackCdrs;
        //处理时间
        Map<String, Object> ps = crmCallBackCdr.getParams();
        LoginUser user = SecurityUtils.getLoginUser();

        // 如果是管理岗位，取所管理的部门，如果不是管理岗位，取个人外呼记录
        if (!adminManager.loginUserIsLeader(user)) {
            crmCallBackCdr.setUserId(user.getUserId());
        }
        
        // 如果是分公司管理员或者质检，取分公司所有数据
        if (adminManager.loginUserIsBranchBoss(user) && !"super".equals(user.getUsername())) {
        	crmCallBackCdr.setMchId(user.getUser().getMchId());
            if(crmCallBackCdr.getUserId() != null){
            	crmCallBackCdr.setUserId(crmCallBackCdr.getUserId());
            }
        }

        //客服质检 电销 看全公司
        if (adminManager.loginUserIsServiceDept(user) || user.getUser().getMchId().intValue() == 1063) {
            crmCallBackCdr.setUserId(null);
            crmCallBackCdr.setMchId(user.getUser().getMchId());
            if (crmCallBackCdr.getParams() !=null && crmCallBackCdr.getParams().get("dataScope")!=null) {
                crmCallBackCdr.getParams().put("dataScope", "");
            }
        }
        
        //客服质检 电销 看全公司
        if (user.getUser().getMchId().intValue() == 1090) {
        	crmCallBackCdr.setUserId(null);
        	crmCallBackCdr.setMchId(null);
        	if (crmCallBackCdr.getParams() !=null && crmCallBackCdr.getParams().get("dataScope")!=null) {
        		crmCallBackCdr.getParams().put("dataScope", "");
        	}
        }

        // 查询数据库
        PageUtils.startPage();
        crmCallBackCdrs = crmCallBackCdrMapper.selectCrmCallBackCdrList(crmCallBackCdr);
        crmCallBackCdrs.stream().forEach(item ->{
            item.setCdrId(item.getId()+"");
            String endTime = StringUtils.isNotEmpty(item.getCdrEndTime()) ? item.getCdrEndTime() :"";
            String brideTime = StringUtils.isNotEmpty(item.getCdrBridgeTime()) ? item.getCdrBridgeTime() :"";
            item.setCdrEndTimeCdrBridgeTime(endTime + "-" + brideTime);
        });
        return crmCallBackCdrs;
    }

    /**
     * 新增回呼话单
     *
     * @param crmCallBackCdr 回呼话单
     * @return 结果
     */
    @Override
    public AjaxResult insertCrmCallBackCdr(CrmCallBackCdr crmCallBackCdr) {
        try {
            // 保存crmId
            // 根据工号 获取二级部门id 和 当前员工所在部门ID
            if (StringUtils.isNotEmpty(crmCallBackCdr.getCdrCalleeCno())) {
                SysUser sysUser = sysUserService.selectUserByAgentId(crmCallBackCdr.getCdrCalleeCno());
                if (Objects.nonNull(sysUser)) {
                    crmCallBackCdr.setMchId(sysUser.getMchId());
                    crmCallBackCdr.setDeptId(sysUser.getDeptId());
                    // 用户id
                    crmCallBackCdr.setUserId(sysUser.getUserId());
                }
            }
            crmCallBackCdr.setId(IdSeqGenerator.getInstance().getId());
            crmCallBackCdr.setCreateTime(DateUtils.getNowDate());
            crmCallBackCdr.setStartTime(DateUtils.getTime());
            String cdrCustomerNumber = crmCallBackCdr.getCdrCustomerNumber();
            // 加密存储 手机号
            // 脱敏手机号
            crmCallBackCdr.setMobileHidden(DesensitizedUtil.mobilePhone(cdrCustomerNumber));
            int i = crmCallBackCdrMapper.insertCrmCallBackCdr(crmCallBackCdr);
            if (i > 0) {
                return AjaxResult.success();
            }
        } catch (Exception e) {
            log.info("新增回呼通话记录失败 e={}", e);
        }
        return AjaxResult.error();
    }

    /**
     * 修改回呼话单
     *
     * @param crmCallBackCdr 回呼话单
     * @return 结果
     */
    @Override
    public int updateCrmCallBackCdr(CrmCallBackCdr crmCallBackCdr) {
        return crmCallBackCdrMapper.updateCrmCallBackCdr(crmCallBackCdr);
    }
    /**
     * 修改回呼录音地址
     *
     * @param map 回呼参数
     * @return 结果
     */
    @Override
    public int updateCrmCallBackCdrById(Map<String, Object> map) {
        return crmCallBackCdrMapper.updateCrmCallBackCdrById(map);
    }


    /**
     * 查询回呼客户信息 2023 精简查询
     */
    @Override
    public AjaxResult getCallBackCustomerInfo(QueryCrmCallBackCustomerInfoVO vo) {
        CrmCallBackCustomerInfo result = new CrmCallBackCustomerInfo();

        log.info("CRM回呼日志===" + JSON.toJSONString(vo));

        //查询客户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //2022-8-29 获取当前用户 是客服座席
        if (adminManager.loginUserIsServiceDept(loginUser)) {
            result.setAllowDetail("1");
        }

        return AjaxResult.success("查询成功", result);
    }


    @Override
    public List<CrmCallBackCdr> selectCrmOutCallRecordByUniqueId(CrmCallBackCdr crmCallBackCdrVo) {
        return crmCallBackCdrMapper.selectCrmOutCallRecordByUniqueId(crmCallBackCdrVo);
    }
}
